package com.gene.tlonpo.service.handler;

import com.gene.tlonpo.guard.Guard;
import com.gene.tlonpo.guard.tool.GuardAggregationTool;
import com.gene.tlonpo.manager.type.GuardManageType;
import com.gene.tlonpo.service.remote.client.TlonpoNettyClient;
import com.gene.tlonpo.service.remote.common.model.DataDto;
import com.gene.tlonpo.service.remote.common.model.DataRespDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;

/**
 * @author geneX
 * 本地处理
 */
@Slf4j
public class TlonpoBusinessHandler implements BusinessHandler {
    /**
     * 对外单例提供
     */
    public static final BusinessHandler tlonpoBusinessHandler = new TlonpoBusinessHandler();

    private static TlonpoNettyClient tlonpoNettyClient = TlonpoNettyClient.TLONPO_NETTY_CLIENT;

    private TlonpoBusinessHandler() {
    }

    @Override
    public DataRespDto localCallback(String bizKey) {
        //本地查询哨兵信息
        List<Guard> guardList = GuardAggregationTool.getGuard(bizKey, GuardManageType.LOCAL);

        if (CollectionUtils.isEmpty(guardList)) {
            log.info("There is no guard of local by bizKey :{}", bizKey);
            return DataRespDto.success("no guard need to be execute",null);
        }

        //本地callback
        guardList.forEach(Guard::callbackAndWrite);

        return DataRespDto.success(null);
    }

    @Override
    public void remoteCallback(DataDto dataDto) {
        tlonpoNettyClient.sendData(dataDto);
    }
}
